package org.dawfinn.droiditarian;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dawfinn.droiditarian.server.data.DeedLocation;
import org.dawfinn.droiditarian.server.data.PMF;

@SuppressWarnings("serial")
public class TestImageServlet extends HttpServlet {

	@SuppressWarnings("unchecked")
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ServletOutputStream output = resp.getOutputStream();

		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query q = pm.newQuery(DeedLocation.class);
		// q.setFilter("image != null");

		List<DeedLocation> locations = (List<DeedLocation>) q.execute();
		boolean written = false;
		for (DeedLocation location : locations) {
			if (location.getImage() != null) {
				resp.setContentType("image/jpeg");
				output.write(locations.get(0).getImage().getBytes());
				output.close();
				written = true;
				System.out.println("writing an image!");
				break;
			}
		}
		if (!written) {
			resp.setContentType("text/html");
			output.println("failed");
			output.close();
		}

		pm.newQuery(DeedLocation.class);
		pm.deletePersistentAll();
		pm.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		ServletInputStream in = req.getInputStream();
		ServletOutputStream out = resp.getOutputStream();

		resp.setContentType(req.getContentType());

		byte[] buf = new byte[1024];
		int n;
		while ((n = in.read(buf)) > 0) {
			out.write(buf, 0, n);
		}

		in.close();
		out.close();
	}

}
